package com.dataseek.iot.sys.service.impl;

import com.dataseek.iot.sys.service.EmailServiceOld;
import com.dataseek.iot.toolkit.auth.redis.config.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 邮箱服务
 */
@Service
public class EmailServiceOldImpl implements EmailServiceOld {
    @Autowired
    private RedisCache redisCache;

//    @Autowired
//    private JavaMailSender javaMailSender;
//
    @Autowired
    private JavaMailSender mailSender;

    @Override
    public String sendVerifyCodeByMail(Integer verifyCode,String email) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("<html><head><title></title></head><body>");
        stringBuilder.append("您好<br/>");
        stringBuilder.append("您的验证码是：").append(verifyCode).append("<br/>");
        stringBuilder.append("您可以复制此验证码并返回至管理系统修改密码页面，以验证您的邮箱。<br/>");
        stringBuilder.append("此验证码只能使用一次，在");
        stringBuilder.append("15");
        stringBuilder.append("分钟内有效。验证成功则自动失效。<br/>");
        stringBuilder.append("如果您没有进行上述操作，请忽略此邮件。");
        MimeMessage mimeMessage = mailSender.createMimeMessage();

        // 发件配置并发送邮件
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            //这里只是设置username 并没有设置host和password，因为host和password在springboot启动创建JavaMailSender实例的时候已经读取了
            mimeMessageHelper.setFrom("dataseek2022@163.com");
            // 用户的邮箱地址
            mimeMessageHelper.setTo(email);
            // 邮件的标题
            mimeMessage.setSubject("邮箱验证-管理系统");
            // 上面所拼接的邮件内容
            mimeMessageHelper.setText(stringBuilder.toString(), true);
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        return "获取验证码成功，请查看移步您的邮箱 "+email+" 查看验证码！";
    }
}
